<template>
  <div>
    <a-drawer
      :title="drawerTitle"
      :visible="visible"
      :destroyOnClose="true"
      :width="1100"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeDrawer"
    >
      <template v-if="currentStep == 1">
        <a-form layout="vertical">
          <a-row :gutter="12" v-if="ids.length > 1">
            <a-col :span="24">
              <a-form-item label="生成方式:">
                <a-radio-group
                  v-model:value="modelRef.buildType"
                  @change="onBuildTypeChange"
                >
                  <!-- <a-radio-button value="1">逐张账单生成</a-radio-button>
              <a-radio-button value="2">按租客合并生成</a-radio-button>
              <a-radio-button value="3">按合同合并生成</a-radio-button> -->

                  <a-radio-button
                    v-for="item in buildTypeList"
                    :key="item.key"
                    :value="item.key"
                    >{{ item.name }}</a-radio-button
                  >
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <div style="background-color: #ececec; padding: 20px">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-card :bordered="false">
                  <p>即将生成通知单份数</p>
                  <p style="font-size: 18px; color: #000">{{ noticeTotal }}</p>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card :bordered="false">
                  <p>合计应收</p>
                  <p style="font-size: 18px; color: #000">
                    {{ noticeAmount }} <span>元</span>
                  </p>
                </a-card>
              </a-col>
            </a-row>
          </div>
          <a-row :gutter="12" style="margin-top: 20px">
            <!-- <a-col :span="24">
              <a-form-item
                label="通知方式:"
                v-bind="validateInfos.checkedNoticeList"
              >
                <a-checkbox
                  v-model:checked="noticeAll"
                  :indeterminate="indeterminate"
                  @change="onNoticeAllChange"
                >
                  全选
                </a-checkbox>
                <a-checkbox-group v-model:value="modelRef.checkedNoticeList">
                  <a-checkbox
                    v-for="item in noticeTypeList"
                    :key="item.key"
                    :value="item.key"
                    >{{ item.name }}</a-checkbox
                  >
                </a-checkbox-group>
              </a-form-item>
            </a-col> -->
          </a-row>
          <a-form-item label="通知单设置" v-bind="validateInfos.tableList">
            <a-table
              :columns="noticeColumns"
              :data-source="noticeListData"
              :loading="noticeListLoading"
              :pagination="false"
              rowKey="buildId"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'txtTemplateId'">
                  <a-select
                    v-model:value="record.txtTemplateId"
                    placeholder=""
                    :options="
                      record.txtTemplate.map((item) => ({
                        value: item.id,
                        label: item.name,
                        ...item,
                      }))
                    "
                    @change="
                      (value, option) => onTxtTemplateChange(option, record)
                    "
                    allowClear
                  >
                  </a-select>
                </template>
                <template v-if="column.key === 'notificationTemplate'">
                  <a-select
                    v-model:value="record.sendTemplateId"
                    placeholder=""
                    :options="
                      record.sendTemplate.map((item) => ({
                        value: item.id,
                        label: item.name,
                        ...item,
                      }))
                    "
                    @change="
                      (value, option) => onSendTemplateChange(option, record)
                    "
                    allowClear
                  >
                  </a-select>
                </template>
                <template v-if="column.key === 'accountId'">
                  <a-select
                    v-model:value="record.accountId"
                    placeholder=""
                    :options="
                      record.accountData.map((item) => ({
                        value: item.id,
                        label: item.name,
                        ...item,
                      }))
                    "
                    @change="(value, option) => onAccountChange(option, record)"
                  >
                  </a-select>
                </template>
              </template>
            </a-table>
          </a-form-item>
          <a-row :gutter="12" style="margin-top: 20px">
            <a-col :span="12" id="code-item">
              <a-form-item>
                <template #label>
                  <span>是否附上收款二维码</span>
                  <text-tip
                    :tips="[
                      '支持在生成的通知单模板的下方附上收款二维码，未配置支付方式或打印模板里未添加收款二维码关键词时开启也不会生效',
                    ]"
                  />
                </template>
                <a-radio-group v-model:value="modelRef.hasQRCode" size="small">
                  <a-radio-button
                    v-for="item in QRTypeList"
                    :key="item.key"
                    :value="item.key"
                    >{{ item.name }}</a-radio-button
                  >
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template #label>
                  <span>通知单生成日期</span>
                  <text-tip
                    :tips="['通知单生成日期将影响通知单模板中的生成日期变量']"
                  />
                </template>
                <a-date-picker
                  v-model:value="modelRef.date"
                  format="YYYY-MM-DD"
                  placeholder=""
                  style="width: 50%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>

      <template v-else>
        <a-form>
          <a-alert
            showIcon
            message="如无通知单接收人请新建，无接收人或接收人信息不完善将无法进行发送。"
            type="info"
            style="margin-top: 10px; margin-bottom: 10px"
          />
          <a-form-item v-bind="validateInfos.receiverList">
            <a-table
              :columns="contactColumns"
              :data-source="contactList"
              :loading="contactListLoading"
              :pagination="contactPagination"
              rowKey="id"
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
              }"
              @change="handleTableChange"
            >
              <template #headerCell="{ title, column }">
                <template v-if="column.key === 'tel'">
                  <span style="color: red">*</span><span> 手机号</span>
                </template>
                <template v-if="column.key === 'email'">
                  <span style="color: red">*</span><span> 邮箱地址 </span>
                </template>
              </template>
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'contact_notice_name'">
                  <span v-if="text">{{ text }}</span>
                  <a v-else href="#" @click.prevent="onAddContactClick(record)"
                    >新增</a
                  >
                </template>
                <template v-if="column.key === 'tel'">
                  <span> {{ text ? text : "-" }}</span>
                </template>
                <template v-if="column.key === 'email'">
                  <span> {{ text ? text : "-" }}</span>
                </template>
                <template v-if="column.key === 'action'">
                  <a
                    href=""
                    @click.prevent="editContact(record)"
                    v-if="record.contact_notice_id"
                    >编辑</a
                  >
                </template>
              </template>
            </a-table>
          </a-form-item>
        </a-form>
      </template>

      <div class="drawer-footer">
        <a-button class="mr-10" @click.prevent="closeDrawer">取消</a-button>
        <template v-if="currentStep == 1">
          <a-button
            type="primary"
            @click.prevent="onNextStep"
            v-if="showNextStep"
          >
            下一步
          </a-button>
          <a-button type="primary" @click.prevent="onSubmit" v-else>
            生成缴费单
          </a-button>
        </template>
        <template v-else>
          <a-button class="mr-10" @click.prevent="onPreviousStep">
            上一步
          </a-button>
          <a-button type="primary" @click.prevent="onSubmit"
            >生成缴费单</a-button
          >
        </template>
      </div>
      <add-contact
        @cancel="addContactClose"
        @success="addContactSuccess"
        :visible="addContactVisible"
        :ownerInfo="{ name: addContactOwnerName, id: addContactOwnerId }"
        :id="editContactId"
      ></add-contact>
    </a-drawer>

    <a-modal
      v-model:visible="progressModalVisible"
      centered
      :footer="null"
      @ok="modal2Visible = false"
    >
      <h3>正在生成中</h3>
      <Progress :percent="progressPercent" style="margin-top: 20px" />
      <p v-if="progressPercent < 100" style="margin-top: 20px">
        正在自动生成中，请勿刷新或关闭本页面
      </p>
      <p v-else style="margin-top: 20px">已成功生成缴费通知单</p>
    </a-modal>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  reactive,
  toRefs,
  toRaw,
  createVNode,
  h,
} from "vue";
import request from "../../../common/utils/request";
import { Form, message, Progress, notification, Modal } from "ant-design-vue";
import { TextTip } from "bl-common-vue3";
import AddContact from "./AddContact.vue";
import moment from "moment";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
const useForm = Form.useForm;
export default defineComponent({
  name: "addNotice",
  components: { TextTip, AddContact, Progress },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    ids: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, context) {
    const router = useRouter();
    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      buildType: 1, //生成方式
      noticeType: [], //通知方式
      hasQRCode: 0, //是否展示二维码：0：否，1：是
      date: moment(), //通知单生成日期(默认今天)
      checkedNoticeList: [],
      tableList: null,
      receiverList: null,
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      tableList: [{ required: true, message: "请选择收支帐户" }],
      receiverList: [{ required: false, message: "请完善通知联系人信息" }],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const noticeListColumns = ref([
      {
        title: "项目名称",
        dataIndex: "villageName",
        width: "15%",
        ellipsis: true,
      },
      {
        title: "楼宇名称",
        dataIndex: "buildName",
        width: "15%",
        ellipsis: true,
      },
      {
        title: "所属公司",
        dataIndex: "company_name",
        width: "16%",
        ellipsis: true,
      },
      {
        title: "文本模板",
        dataIndex: "txtTemplateId",
        key: "txtTemplateId",
        width: "18%",
      },
      {
        title: "通知模板",
        dataIndex: "notificationTemplate",
        key: "notificationTemplate",
        width: "18%",
      },
      {
        title: "收支账户",
        dataIndex: "accountId",
        key: "accountId",
        width: "18%",
      },
    ]);

    const billOwnerListColumns = ref([
      {
        title: "租客名称",
        dataIndex: "ownerName",
        width: "11%",
        ellipsis: true,
      },
      {
        title: "所属公司",
        dataIndex: "company_name",
        width: "11%",
        ellipsis: true,
      },
      {
        title: "项目名称",
        dataIndex: "villageName",
        width: "12%",
        ellipsis: true,
      },
      {
        title: "楼宇名称",
        dataIndex: "buildName",
        width: "12%",
        ellipsis: true,
      },
      {
        title: "文本模板",
        dataIndex: "txtTemplateId",
        key: "txtTemplateId",
        width: "18%",
      },
      {
        title: "通知模板",
        dataIndex: "notificationTemplate",
        key: "notificationTemplate",
        width: "18%",
      },
      {
        title: "收支账户",
        dataIndex: "accountId",
        key: "accountId",
        width: "18%",
      },
    ]);

    const contractListColumns = ref([
      {
        title: "合同编号",
        dataIndex: "contract_number",
        width: "12%",
      },
      {
        title: "租客名称",
        dataIndex: "ownerName",
        width: "10%",
        ellipsis: true,
      },
      {
        title: "所属公司",
        dataIndex: "company_name",
        width: "11%",
        ellipsis: true,
      },
      {
        title: "项目名称",
        dataIndex: "villageName",
        width: "11%",
        ellipsis: true,
      },
      {
        title: "楼宇名称",
        dataIndex: "buildName",
        width: "11%",
        ellipsis: true,
      },
      {
        title: "文本模板",
        dataIndex: "txtTemplateId",
        key: "txtTemplateId",
        width: "15%",
      },
      {
        title: "通知模板",
        dataIndex: "notificationTemplate",
        key: "notificationTemplate",
        width: "15%",
      },
      {
        title: "收支账户",
        dataIndex: "accountId",
        key: "accountId",
        width: "15%",
      },
    ]);

    const noticeColumns = computed(() => {
      return props.ids?.length > 1 ? modelRef.buildType == 1 || modelRef.buildType == 2 ? billOwnerListColumns.value : contractListColumns.value : noticeListColumns.value ;
    });

    const state = reactive({
      indeterminate: false,
      noticeAll: false,

      buildTypeList: [],
      noticeTypeList: [],
      QRTypeList: [],

      noticeTotal: null,
      noticeAmount: null,

      noticeListData: [], //通知单设置，table数据
      noticeListLoading: false,
      showNextStep: false,

      selectedRowKeys: [],
      selectedRows: [],

      contactList: [], //通知单接收人table数据
    });

    const onNoticeAllChange = (e) => {
      if (e.target.checked) {
        modelRef.checkedNoticeList = state.noticeTypeList.map((item) => {
          return item.key;
        });
        modelRef.checkedNoticeList = state.noticeTypeList.map((item) => {
          return item.key;
        });
        state.indeterminate = false;
        state.noticeAll = true;
      } else {
        modelRef.checkedNoticeList = [];
        state.indeterminate = false;
      }
    };

    watch(
      () => modelRef.checkedNoticeList,
      (val) => {
        state.indeterminate =
          !!val.length && val.length < state.noticeTypeList.length;
        state.noticeAll = val.length === state.noticeTypeList.length;

        // [1:下载打印； 2：短信通知； 3：邮件通知； 4：公众号通知]
        if (val.includes(2) || val.includes(3) || val.includes(4)) {
          state.showNextStep = true;
        } else {
          state.showNextStep = false;
        }

        // 通知设置table中的短信配置&&邮件配置是否显示
        if (val.includes(2)) {
          messageChecked.value = true;
        } else {
          messageChecked.value = false;
        }
        if (val.includes(3)) {
          emailChecked.value = true;
        } else {
          emailChecked.value = false;
        }
        if (val.includes(4)) {
          weChatPublicChecked.value = true;
        } else {
          weChatPublicChecked.value = false;
        }
      }
    );

    /**
     * @description: 初始化
     */
    const init = () => {
      getBasicInfo();
    };

    const checkTable = () => {
      for (let item of state.noticeListData) {
        if (!item.accountId) {
          return null;
        }
      }
      return true;
    };

    const getBasicInfo = () => {
      state.noticeListLoading = true;
      request
        .post("/org", "/notice/buildInit", {
          billIds: props.ids,
          build_type: modelRef.buildType,
        })
        .then((res) => {
          state.buildTypeList = res.initData?.buildType;
          state.noticeTypeList = res.initData?.noticeType;
          state.QRTypeList = res.initData?.hasQrcode;
          state.noticeTotal = res.returnData?.noticeTotal;
          state.noticeAmount = res.returnData?.noticeAmount;
          state.noticeListData = res.returnData?.noticeData;
          let needChange = false;
          if (
            res.returnData.noticeData &&
            res.returnData.noticeData.length > 0
          ) {
            res.returnData.noticeData.map((item) => {
              // 默认为false，未配置
              item.hasMessage = false;
              item.hasEmail = false;
              item.hasWeChatPublic = false;

              if (item.sendTemplate) {
                item.sendTemplateId = item.sendTemplate.id;
                if (
                  item.sendTemplate.type_json &&
                  item.sendTemplate.type_json.length > 0
                ) {
                  item.sendTemplate.type_json.map((typeItem) => {
                    if (typeItem.mode == 1 && typeItem.status == 1) {
                      item.hasMessage = true;
                    }
                    if (typeItem.mode == 2 && typeItem.status == 1) {
                      item.hasEmail = true;
                    }
                    if (typeItem.mode == 3 && typeItem.status == 1) {
                      item.hasWeChatPublic = true;
                    }
                  });
                }
              }
              if (item?.txtTemplate?.length) {
                needChange = true;
                let current = item.txtTemplate[0];
                item.txtTemplateId = current.id;
                item.selectedTxtTemplate = {
                  ...current,
                  value: current.id,
                  label: current.name,
                };
                modelRef.checkedNoticeList.push(1);
              }
              // [1:下载打印； 2：短信通知； 3：邮件通知； 4：公众号通知]
              if (item?.sendTemplate?.length) {
                needChange = true;
                let current = item.sendTemplate[0];
                item.sendTemplateId = current.id;
                if (modelRef.checkedNoticeList.length) {
                  modelRef.checkedNoticeList =
                    modelRef.checkedNoticeList.concat(
                      item.sendTemplate[0].type_json
                        .map((typeJson) => {
                          return {
                            mode: typeJson.mode + 1,
                            type: typeJson.status,
                          };
                        })
                        .filter((v) => v.type == 1)
                        .map((i) => i.mode)
                    );
                } else {
                  modelRef.checkedNoticeList = item.sendTemplate[0].type_json
                    .map((typeJson) => {
                      return {
                        mode: typeJson.mode + 1,
                        type: typeJson.status,
                      };
                    })
                    .filter((v) => v.type == 1)
                    .map((i) => i.mode);
                }
                item.noticeType = modelRef.checkedNoticeList;
              }
              if (item?.accountData?.length) {
                needChange = true;
                let current = item.accountData[0];
                item.accountId = current.id;
                item.account = {
                  ...current,
                  value: current.id,
                  label: current.name,
                };
              }
            });
          }
          if (needChange) {
            modelRef.tableList = checkTable();
          }
        })
        .catch((err) => {
          console.log(err);
          if (err.code == 60024) {
            Modal.info({
              title: "提示",
              content: () => err.msg,
              centered: true,
              okText: () => "确定",
            });
          } else if (err.code == 60025) {
            Modal.confirm({
              title: "提示",
              content: () =>
                h("div", { style: "color:#999;" }, [
                  h("p", {}, `以下楼宇未配置通知单打印模板：`),
                  h("p", { style: "font-size:16px;color:#333" }, err.msg),
                ]),
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "前往设置",
              onOk() {
                context.emit("closeDrawer");
                router.push({
                  name: "noticeSetting",
                  query: { type: "print" },
                });
              },
              onCancel() {
                context.emit("closeDrawer");
              },
            });
          } else if (err.code == 60026) {
            Modal.confirm({
              title: "提示",
              content: () =>
                h("div", { style: "color:#999;" }, [
                  h("p", {}, `以下楼宇未配置通知单发送模板：`),
                  h("p", { style: "font-size:16px;color:#333" }, err.msg),
                ]),
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "前往设置",
              onOk() {
                context.emit("closeDrawer");
                router.push({ name: "noticeSetting", query: { type: "send" } });
              },
              onCancel() {
                context.emit("closeDrawer");
              },
            });
          }
        })
        .finally(() => {
          state.noticeListLoading = false;
        });
    };

    const progressModalVisible = ref(false);
    const progressPercent = ref(0);

    const checkReceiver = () => {
      for (let item of state.contactList) {
        if (!item.contact_notice_id) {
          return null;
        }
      }
      return true;
    };

    const taskKey = ref(""); //执行打包下载操作需要返回给后端的key
    let progressTimer = null;
    const progressTimerCount = ref(0); //定时器请求次数

    const realSubmit = () => {
      validate().then(() => {
        let params = { ...toRaw(modelRef), needMsg: true };
        console.log(params);
        let submitParams = {
          buildType: params.buildType,
          noticeTotal: state.noticeTotal,
          noticeAmount: state.noticeAmount,
          noticeType: modelRef.checkedNoticeList,
          hasQrcode: params.hasQRCode,
          buildDate: params.date
            ? moment(params.date).format("YYYY-MM-DD")
            : "",
        };
        let noticeData = [];
        if (state.noticeListData.length > 0) {
          state.noticeListData.map((item) => {
            let tmp = {};
            tmp.buildId = item.buildId;
            tmp.buildName = item.buildName;
            tmp.txtTemplate = item.selectedTxtTemplate;

            tmp.account = item.account;
            tmp.sendTemplateId = item.sendTemplateId;
            tmp.sendTemplate = item?.sendTemplate;
            tmp.org_branch_id = item?.org_branch_id;
            tmp.is_branch_account = item?.is_branch_account;
            tmp.noticeType = [...new Set(item?.noticeType)];
            noticeData.push(tmp);
          });
          noticeData.forEach((item) => {
            item.applySms = 0;
            item.applyEmail = 0;
            item.applyWechatSms = 0;
            if (item?.sendTemplateId && item?.sendTemplate?.length) {
              let typeList = item?.sendTemplate.filter(
                (v) => v.id == item?.sendTemplateId
              );

              typeList.forEach((type) => {
                if (type?.type_json.length) {
                  type?.type_json.forEach((v) => {
                    item.noticeData;
                    // 短信通知
                    if (v.mode == 1) {
                      item.applySms = v.status == 0 ? 0 : 1;
                    }
                    // 邮件通知
                    if (v.mode == 2) {
                      item.applyEmail = v.status == 0 ? 0 : 1;
                    }
                    // 公众号通知
                    if (v.mode == 3) {
                      item.applyWechatSms = v.status == 0 ? 0 : 1;
                    }
                  });
                }
              });
            }
            item.sendTemplate = undefined;
          });
        }
        submitParams.noticeData = noticeData;
        submitParams.noticeOwnerList = state.selectedRows;
        console.log(submitParams);
        request
          .post("/org", "/notice/build", {
            buildData: { ...submitParams },
            billIds: props.ids,
          })
          .then((res) => {
            taskKey.value = res.task_key;

            // [1:下载打印； 2：短信通知； 3：邮件通知]
            if (modelRef.checkedNoticeList.includes(1)) {
              progressModalVisible.value = true;
              progressTimer = setInterval(() => {
                if (progressPercent.value >= 100) {
                  clearInterval(progressTimer);
                  message.success("生成成功");
                  setTimeout(() => {
                    progressModalVisible.value = false;
                    context.emit("success");
                  }, 1500);
                }
                if (progressTimerCount.value > 300) {
                  //定时器请求次数，当progressTimerCount>300（定时器五分钟）后，取消定时器，关闭进度条弹窗，提示失败,并清除taskKey
                  clearInterval(progressTimer);
                  notification.error({
                    description: "服务异常,请稍后重试",
                    onClick: () => {
                      console.log("Notification Clicked!");
                    },
                  });
                  setTimeout(() => {
                    progressModalVisible.value = false;
                  }, 1500);
                }
                progressTimerCount.value++;
                request
                  .get("/org", "/notice/downloadProgress", {
                    task_key: taskKey.value,
                  })
                  .then((res) => {
                    if (
                      progressTimerCount.value > 120 &&
                      res.progressData.success == 0
                    ) {
                      //两分钟后，任无成功进程，取消定时器，关闭进度条弹窗，提示失败,并清除taskKey
                      clearInterval(progressTimer);
                      notification.error({
                        description: "服务异常,请稍后重试",
                        onClick: () => {
                          console.log("Notification Clicked!");
                        },
                      });
                      setTimeout(() => {
                        progressModalVisible.value = false;
                      }, 1500);
                    }
                    if (Number(res.progressData.taskCount) > 0) {
                      progressPercent.value =
                        (Number(res.progressData.success) /
                          Number(res.progressData.taskCount)) *
                        100;
                    }
                    if (res.progressData.zipFile.fileUrl) {
                      window.open(res.progressData.zipFile.fileUrl);
                    }
                    const percent = Math.round(progressPercent.value);
                    progressPercent.value = percent >= 100 ? 100 : percent;
                  });
              }, 1000);
            } else {
              message.success("生成成功");
              context.emit("success");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      });
    };

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      if (!modelRef.tableList) {
        modelRef.tableList = checkTable();
      }
      let isSubmit = false;
      let isSubmitList = [];
      for (let item of state.noticeListData) {
        if (item.txtTemplateId || item.sendTemplateId) {
          isSubmit = true;
          isSubmitList.push(item);
        }
      }
      if (isSubmitList.length !== state.noticeListData.length) {
        message.warn("文本模板和通知模板必须至少选择一个");
        return;
      }
      if (isSubmit) {
        if (currentStep.value == 1) {
          realSubmit();
        } else {
          if (state.selectedRows.length == 0) {
            message.warning("请至少选择一个通知单接收人");
          } else {
            if (!modelRef.receiverList) {
              modelRef.receiverList = checkReceiver();
            }
            realSubmit();
          }
        }
      } else {
        message.warn("文本模板和通知模板必须至少选择一个");
      }
    };

    const onBuildTypeChange = (e) => {
      console.log(e.target.value);
      getBasicInfo();
    };

    const currentStep = ref(1);
    const onPreviousStep = () => {
      currentStep.value = 1;
    };
    const onNextStep = () => {
      let isSubmit = false;
      let isSubmitList = [];
      for (let item of state.noticeListData) {
        if (item.txtTemplateId || item.sendTemplateId) {
          isSubmit = true;
          isSubmitList.push(item);
        }
      }
      if (isSubmitList.length !== state.noticeListData.length) {
        message.warn("文本模板和通知模板必须至少选择一个");
        return;
      }
      if (isSubmit) {
        validate().then(() => {
          currentStep.value = 2;
          getContactList();
        });
      } else {
        message.warn("文本模板和通知模板必须至少选择一个");
      }
    };
    const closeDrawer = () => {
      context.emit("closeDrawer");
    };

    const messageChecked = ref(false);
    const emailChecked = ref(false);
    const weChatPublicChecked = ref(false);

    const contactColumns = ref([
      {
        title: "租客名称",
        dataIndex: "name",
        width: "20%",
        ellipsis: true,
      },
      {
        title: "通知单联系人",
        dataIndex: "contact_notice_name",
        key: "contact_notice_name",
        width: "20%",
      },
      {
        dataIndex: "tel",
        key: "tel",
        width: "20%",
      },
      {
        dataIndex: "email",
        key: "email",
        width: "30%",
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "action",
        width: "10%",
      },
    ]);

    const contactListLoading = ref(false);

    const getContactList = () => {
      contactListLoading.value = true;
      request
        .post("/org", "/notice/getNoticeOwner", {
          billIds: props.ids,
          build_type: modelRef.buildType,
          page: page.value,
          limit: limit.value,
        })
        .then((res) => {
          state.contactList = res.list;
          contactListLoading.value = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getContactList();
    };

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const contactPagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const addContactVisible = ref(false);

    const addContactClose = () => {
      addContactVisible.value = false;
    };

    const addContactSuccess = () => {
      addContactClose();
      getContactList();
    };

    const onAccountChange = (option, record) => {
      record.account = option;
      record.accountId = option.id;
      modelRef.tableList = checkTable();
    };

    const onTxtTemplateChange = (option, record) => {
      if (!option) {
        record.selectedTxtTemplate = [];
        record.txtTemplateId = null;
        modelRef.checkedNoticeList = modelRef.checkedNoticeList.filter(
          (item) => item != 1
        );
        record.noticeType = modelRef.checkedNoticeList;
        return;
      }
      record.selectedTxtTemplate = option;
      record.txtTemplateId = option.id;
      if (modelRef?.checkedNoticeList.length) {
        modelRef.checkedNoticeList = modelRef.checkedNoticeList.concat(1);
        record.noticeType = modelRef.checkedNoticeList;
      } else {
        modelRef.checkedNoticeList = [1];
        record.noticeType = modelRef.checkedNoticeList;
      }
      modelRef.tableList = checkTable();
    };

    const onSendTemplateChange = (option, record) => {
      if (!option) {
        modelRef.checkedNoticeList = [];
        if (record?.selectedTxtTemplate?.id) {
          modelRef.checkedNoticeList = modelRef.checkedNoticeList.concat(1);
        }
        record.noticeType = [];
        return;
      }
      modelRef.checkedNoticeList = option.type_json
        .map((typeJson) => {
          return {
            mode: typeJson.mode + 1,
            type: typeJson.status,
          };
        })
        .filter((v) => v.type == 1)
        .map((i) => i.mode);
      record.noticeType = modelRef.checkedNoticeList;
      if (record?.selectedTxtTemplate?.id) {
        modelRef.checkedNoticeList = modelRef.checkedNoticeList.concat(1);
        record.noticeType = modelRef.checkedNoticeList;
      }
    };

    const addContactOwnerName = ref("");
    const addContactOwnerId = ref(0);

    const editContactId = ref(null);

    const onAddContactClick = (record) => {
      addContactOwnerName.value = record.name;
      addContactOwnerId.value = record.id;
      editContactId.value = 0;
      addContactVisible.value = true;
    };

    const drawerTitle = computed(() => {
      return currentStep.value == 1 ? "生成缴费通知单" : "通知单接收人";
    });

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys, selectedRows);
      state.selectedRowKeys = selectedRowKeys;
      state.selectedRows = selectedRows;
      if (selectedRows.length > 0) {
        rulesRef.receiverList[0].required = true;
        modelRef.receiverList = checkReceiver();
      }
    };

    const editContact = (record) => {
      addContactOwnerName.value = record.name;
      editContactId.value = record.contact_notice_id;
      addContactVisible.value = true;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          currentStep.value = 1;
          rulesRef.receiverList[0].required = false;
          state.contactList = [];
          state.selectedRowKeys = [];
          state.selectedRows = [];
          init();
        } else {
          // 关闭时重置数据
          resetFields();
        }
      }
    );

    watch(
      () => progressModalVisible.value,
      (val) => {
        console.log("progressModalVisible.value", progressModalVisible.value);
        if (val) {
          // 打开时初始化数据
        } else {
          // 关闭时重置数据
          taskKey.value = "";
          progressTimerCount.value = 0;
          progressPercent.value = 0;
          clearInterval(progressTimer);
        }
      }
    );

    return {
      closeDrawer,
      onSubmit,
      modelRef,
      validateInfos,
      onNoticeAllChange,
      ...toRefs(state),
      currentStep,
      onPreviousStep,
      onNextStep,
      onBuildTypeChange,

      noticeListColumns,

      messageChecked,
      emailChecked,
      weChatPublicChecked,

      contactPagination,

      addContactVisible,
      addContactClose,
      addContactSuccess,

      onAccountChange,
      onTxtTemplateChange,

      contactColumns,
      onAddContactClick,
      addContactOwnerName,
      addContactOwnerId,
      editContactId,

      drawerTitle,
      contactListLoading,
      onSelectChange,
      progressModalVisible,
      progressPercent,
      editContact,

      onSendTemplateChange,
      noticeColumns,
      handleTableChange,
    };
  },
});
</script>

<style lang="less" scoped>
#code-item {
  :deep(.ant-radio-button-wrapper) {
    padding-left: 25px;
    padding-right: 25px;
  }
}

:deep(.ant-card-body) {
  height: 130px;
}
</style>
